<?php
/**
 * 版本控制器基类
 * @author sunhaoqiang(shqdev@163.com)
 * @time: 2020-01-18 10:03
*/
namespace app\common\tools;

abstract class Version
{
    abstract public function run();

    protected $header = [
        'Access-Control-Allow-Origin'     => '*',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, authKey, Accept, Origin',
    ];

    public static function init()
    {
        return new static();
    }

    /**
     * 接口数据返回
     *
     * @param integer $code 项目自定义状态码| 暂时定为http状态码，后期可能改回项目自定义状态码
     * @param string $msg 项目自定义消息
     * @param [Boolean|Array|String] $data 返回数据
     * @return \think\response\Json
     * @author sunhaoqiang(shqdev@163.com)
     * @time 2020-01-18 12:59
     */
    public function res($code = 200, $msg = '', $data = null)
    {
        $res = [
            'status' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        //$this->initialize();
        return json($res, $code, $this->header); //http状态码
    }

    public function success($data = null)
    {
        return $this->res(200, '请求成功', $data);
    }

    public function error($data = null)
    {
        return $this->res(500, '请求失败', $data);
    }

    public function initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
        }

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            }
        }
    }

}
